package spring.aop.retry;

import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.core.Ordered;

public class ConcurrentOperationExecutor implements Ordered {
    private static final int DEEFAULT_MAX_RETRIES = 2;
    private int maxRetries = DEEFAULT_MAX_RETRIES;
    private int order = 1;

    public int getOrder() {
        return this.order;
    }

    public void setMaxRetries(int maxRetries) {
        this.maxRetries = maxRetries;
    }

    public void setOrder(int order) {
        this.order = order;
    }

    public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {

        int numAttempts = 0;
        Exception lockFailureException;
        do {
            numAttempts++;
            System.out.println("Try times:" + numAttempts);
            try {
                return pjp.proceed();
            } catch (Exception ex) {
                lockFailureException = ex;
            }
        } while (numAttempts <= this.maxRetries);
        System.out.println("Try error:" + numAttempts);
        throw lockFailureException;
    }
}
